Return type | Name and parameters |
---|---|
boolean
|
any(Closure predicate)
Iterates over the contents of an Array, and checks whether a predicate is valid for at least one element. |
boolean
|
asBoolean()
Coerces an object array to a boolean value. |
Object
|
asType(Class type)
Converts the given array to either a List, Set, or SortedSet. |
Object
|
average()
Averages the items in an array. |
Object
|
average(Closure closure)
Averages the result of applying a closure to each item of an array. |
List
|
chop(int chopSizes)
Chops the array into pieces, returning lists with sizes corresponding to the supplied chop sizes. |
List
|
collate(int size)
Collates an array. |
List
|
collate(int size, boolean keepRemainder)
Collates this array into sub-lists. |
List
|
collate(int size, int step)
Collates an array into sub-lists. |
List
|
collate(int size, int step, boolean keepRemainder)
Collates this array into sub-lists. |
List
|
collect(Closure transform)
Iterates through this Array transforming each item into a new value using the transform closure, returning a list of transformed values.
|
Object
|
collect(Object collector, Closure transform)
Iterates through this Array transforming each item into a new value using the transform closure
and adding it to the supplied collector .
|
Map
|
collectEntries()
A variant of collectEntries using the identity closure as the transform. |
Map
|
collectEntries(Closure transform)
Iterates through this array transforming each item using the transform closure
and returning a map of the resulting transformed entries.
|
Map
|
collectEntries(Map collector)
A variant of collectEntries using the identity closure as the transform. |
Map
|
collectEntries(Map collector, Closure transform)
Iterates through this array transforming each item using the transform closure
and returning a map of the resulting transformed entries.
|
Map
|
collectEntries(Map collector, Function keyTransform, Function valueTransform)
A variant of collectEntries for arrays with separate functions for transforming the keys and values. |
Map
|
collectEntries(Function keyTransform, Function valueTransform)
A variant of collectEntries for arrays with separate functions for transforming the keys and values. |
List
|
collectMany(Closure projection)
Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list. |
Object
|
collectMany(Object collector, Closure projection)
Projects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list. |
boolean
|
contains(Object value)
Checks whether the array contains the given value. |
Number
|
count(Closure predicate)
Counts the number of occurrences which satisfy the given closure from inside this array. |
Number
|
count(Object value)
Counts the number of occurrences of the given value inside this array. |
Map
|
countBy()
Creates a multiset-like map of the array members. |
Map
|
countBy(Closure closure)
Sorts all array members into groups determined by the supplied mapping closure and counts the group size. |
Object[]
|
drop(int num)
Drops the given number of elements from the head of this array if they are available. |
Object[]
|
dropRight(int num)
Drops the given number of elements from the tail of this array if they are available. |
Object[]
|
dropWhile(Closure condition)
Create a suffix of the given array by dropping as many elements as possible from the front of the original array such that calling the given closure condition evaluates to true when passed each of the dropped elements. |
Object[]
|
each(Closure closure)
Iterates through an array passing each array entry to the given closure. |
Object[]
|
eachWithIndex(Closure closure)
Iterates through an array, passing each array element and the element's index (a counter starting at zero) to the given closure. |
boolean
|
equals(List right)
Determines if the contents of this array are equal to the contents of the given list, in the same order. |
boolean
|
every(Closure predicate)
Used to determine if the given predicate closure is valid (i.e. returns true for all items in this Array).
|
Object
|
find(Closure condition)
Finds the first element in the array that matches the given closure condition. |
List
|
findAll()
Finds the elements of the array matching the IDENTITY Closure (i.e. matching Groovy truth). |
List
|
findAll(Closure condition)
Finds all elements of the array matching the given Closure condition. |
int
|
findIndexOf(Closure condition)
Iterates over the elements of an array and returns the index of the first item that satisfies the condition specified by the closure. |
int
|
findIndexOf(int startIndex, Closure condition)
Iterates over the elements of an array, starting from a specified index, and returns the index of the first item that satisfies the condition specified by the closure. |
List
|
findIndexValues(Closure condition)
Iterates over the elements of an array and returns the index values of the items that match the condition specified in the closure. |
List
|
findIndexValues(Number startIndex, Closure condition)
Iterates over the elements of an array, starting from a specified index, and returns the index values of the items that match the condition specified in the closure. |
int
|
findLastIndexOf(Closure condition)
Returns the index of the last item that matches the specified condition. |
int
|
findLastIndexOf(int lowerBound, Closure condition)
Returns the index of the last item that matches the specified condition that is at or beyond the given index. |
Object
|
findResult()
Iterates through the Array stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Closure condition)
Iterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Object defaultResult)
Iterates through the Array stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Object defaultResult, Closure condition)
Iterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. |
Collection
|
findResults()
Iterates through the Array collecting any non-null results. |
Collection
|
findResults(Closure filteringTransform)
Iterates through the Array transforming items using the supplied closure and collecting any non-null results. |
Object
|
first()
Returns the first item from the array. |
List
|
flatten()
Flattens an array. |
Collection
|
flattenMany(Closure transform)
Flatten an array. |
List
|
getAt(EmptyRange range)
Supports the subscript operator for an object array with an EmptyRange. |
List
|
getAt(IntRange range)
Supports the subscript operator for an object array with an IntRange giving the desired indices. |
List
|
getAt(ObjectRange range)
Supports the subscript operator for an object array with an ObjectRange giving the desired indices. |
List
|
getAt(Range range)
Supports the subscript operator for an object array with a range giving the desired indices. |
List
|
getAt(Collection indices)
Selects a List of items from an array using a Collection to identify the indices to be selected. |
IntRange
|
getIndices()
Returns indices of the array. |
List
|
grep()
Iterates over the array returning each element that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth. |
List
|
grep(Object filter)
Iterates over the array of items and returns a collection of items that match the given filter - calling the DefaultGroovyMethods#isCase(Object,Object) method used by switch statements. |
Map
|
groupBy(Closure closure)
Sorts all array members into groups determined by the supplied mapping closure. |
Map
|
groupBy(Object closures)
Sorts all array members into (sub)groups determined by the supplied mapping closures as per the Iterable variant of this method. |
Map
|
groupBy(List closures)
Sorts all array members into (sub)groups determined by the supplied mapping closures as per the list variant of this method. |
Object
|
head()
Returns the first item from the Object array. |
int
|
indexOf(Object object)
Returns the index of the first occurrence of the specified element in the array. |
Object[]
|
init()
Returns the items from the Object array excluding the last item. |
Object
|
inject(Closure closure)
Iterates through the given array, passing the first two elements to the closure. |
Object
|
inject(Object initialValue, Closure closure)
Iterates through the given array, passing in the initial value and the first element to the closure. |
Iterator
|
iterator()
Returns an Iterator which traverses the given array in index order. |
String
|
join()
Concatenates the string representation of each item in this array. |
String
|
join(String separator)
Concatenates the string representation of each item in this array, with the given String as a separator between each item. |
Object
|
last()
Returns the last item from the array. |
int
|
lastIndexOf(Object object)
Returns the index of the last occurrence of the specified element in the array. |
Object
|
max()
Adds max() method to Object arrays. |
Object
|
max(Closure closure)
Selects the maximum value found from the Object array using the closure to determine the correct ordering. |
Object
|
max(Comparator comparator)
Selects the maximum value found from the Object array using the given comparator. |
Object
|
min()
Adds min() method to Object arrays. |
Object
|
min(Closure closure)
Selects the minimum value found from the Object array using the closure to determine the correct ordering. |
Object
|
min(Comparator comparator)
Selects the minimum value found from the Object array using the given comparator. |
Object[]
|
minus(Iterable removeMe)
Creates a new array composed of the elements of the first array minus the elements of the given Iterable. |
Object[]
|
minus(Object removeMe)
Creates a new array composed of the elements of the given array minus every occurrence the given object. |
Object[]
|
minus(Object[] removeMe)
Creates a new array composed of the elements of the first array minus the elements of the given array. |
Object[]
|
plus(Iterable right)
Creates an array containing elements from an original array plus those from an Iterable. |
Object[]
|
plus(Object right)
Creates an array containing elements from an original array plus an additional appended element. |
Object[]
|
plus(Object[] right)
Creates an array as a union of two arrays. |
Object[]
|
plus(Collection right)
Creates an array containing elements from an original array plus those from a Collection. |
Object[]
|
reverse()
Creates a new array containing items which are the same as this array but in reverse order. |
Object[]
|
reverse(boolean mutate)
Reverses the items in an array. |
Object[]
|
reverseEach(Closure closure)
Iterates over each element of the array in the reverse order. |
void
|
shuffle()
Randomly reorders the elements of the specified array. |
void
|
shuffle(Random rnd)
Randomly reorders the elements of the specified array using the specified random instance as the source of randomness. |
Object[]
|
shuffled()
Creates a new array containing the elements of the specified array but in a random order. |
Object[]
|
shuffled(Random rnd)
Creates a new array containing the elements of the specified array but in a random order using the specified random instance as the source of randomness. |
int
|
size()
Provides the standard Groovy size() method for an array.
|
Object[]
|
sort()
Modifies this array so that its elements are in sorted order. |
Object[]
|
sort(boolean mutate)
Sorts the given array into sorted order. |
Object[]
|
sort(boolean mutate, Closure closure)
Modifies this array so that its elements are in sorted order using the Closure to determine the correct ordering. |
Object[]
|
sort(boolean mutate, Comparator comparator)
Modifies this array so that its elements are in sorted order as determined by the given comparator. |
Object[]
|
sort(Closure closure)
Sorts the elements from this array into a newly created array using the Closure to determine the correct ordering. |
Object[]
|
sort(Comparator comparator)
Sorts the given array into sorted order using the given comparator. |
Collection
|
split(Closure closure)
Splits all items into two collections based on the closure condition. |
Stream
|
stream()
Returns a sequential Stream with the specified array as its source. |
Object
|
sum()
Sums the items in an array. |
Object
|
sum(Closure closure)
Sums the result of applying a closure to each item of an array. |
Object
|
sum(Object initialValue)
Sums the items in an array, adding the result to some initial value. |
Object
|
sum(Object initialValue, Closure closure)
Sums the result of applying a closure to each item of an array to some initial value. |
Object[]
|
swap(int i, int j)
Swaps two elements at the specified positions. |
Object[]
|
tail()
Returns the items from the array excluding the first item. |
Object[]
|
take(int num)
Returns the first num elements from the head of this array.
|
Object[]
|
takeRight(int num)
Returns the last num elements from the tail of this array.
|
Object[]
|
takeWhile(Closure condition)
Returns the longest prefix of this array where each element passed to the given closure evaluates to true. |
List
|
toList()
Converts this array to a List of the same size, with each element added to the list. |
Set
|
toSet()
Converts this array to a Set, with each unique element added to the set. |
Object[]
|
toSorted()
Returns a sorted version of the given array using the supplied comparator. |
Object[]
|
toSorted(Closure closure)
Sorts the elements from this array into a newly created array using the Closure to determine the correct ordering. |
Object[]
|
toSorted(Comparator comparator)
Returns a sorted version of the given array using the supplied comparator to determine the resulting order. |
SpreadMap
|
toSpreadMap()
Creates a spreadable map from this array. |
String
|
toString()
Returns the string representation of the given array. |
Object[]
|
toUnique()
Returns a new Array containing the items from the original Array but with duplicates removed using the natural ordering of the items in the array. |
Object[]
|
toUnique(Closure closure)
Returns a new Array containing the items from the original Array but with duplicates removed with the supplied closure determining which items are unique. |
Object[]
|
toUnique(Comparator comparator)
Returns a new Array containing the items from the original Array but with duplicates removed with the supplied comparator determining which items are unique. |
Object[]
|
union(Iterable right)
Creates an Object array containing elements from an original array plus those from an Iterable. |
Object[]
|
union(Object right)
Creates an Object array containing elements from an original array plus an additional appended element. |
Object[]
|
union(Object[] right)
Creates an Object array as a union of two arrays. |
Object[]
|
union(Collection right)
Creates an object array containing elements from an original array plus those from a Collection. |
Map
|
withCollectedKeys(Map collector, Function keyTransform)
A variant of withCollectedKeys for arrays. |
Map
|
withCollectedKeys(Function keyTransform)
A variant of withCollectedKeys for arrays. |
Map
|
withCollectedValues(Map collector, Function valueTransform)
A variant of withCollectedValues for arrays. |
Map
|
withCollectedValues(Function valueTransform)
A variant of withCollectedValues for arrays. |
addShutdownHook
, any
, any
, asBoolean
, asType
, collect
, collect
, collect
, dump
, each
, eachMatch
, eachMatch
, eachWithIndex
, every
, every
, find
, find
, findAll
, findAll
, findIndexOf
, findIndexOf
, findIndexValues
, findIndexValues
, findLastIndexOf
, findLastIndexOf
, findResult
, findResult
, findResult
, findResult
, getAt
, getMetaClass
, getMetaPropertyValues
, getProperties
, grep
, grep
, hasProperty
, identity
, inject
, inject
, inspect
, invokeMethod
, is
, isCase
, isNotCase
, iterator
, metaClass
, print
, print
, printf
, printf
, println
, println
, println
, putAt
, respondsTo
, respondsTo
, setMetaClass
, split
, sprintf
, sprintf
, stream
, tap
, toString
, use
, use
, use
, with
, with
, withCloseable
, withMethodClosure
, withStream
, withTraits
Iterates over the contents of an Array, and checks whether a predicate is valid for at least one element.
predicate
- the closure predicate used for matchingCoerces an object array to a boolean value. An Object array is false if the array is of length 0. and to true otherwise
Converts the given array to either a List, Set, or SortedSet. If the given class is something else, the call is deferred to DefaultGroovyMethods#asType(Object,Class).
type
- the desired classAverages the items in an array. This is equivalent to invoking the "plus" method on all items in the array and then dividing by the total count using the "div" method for the resulting sum.
assert 3 == ([1, 2, 6] as Integer[]).average()
Averages the result of applying a closure to each item of an array.
array.average(closure)
is equivalent to:
array.collect(closure).average()
.
def (nums, strings) = [[1, 3] as Integer[], ['to', 'from'] as String[]] assert 20 == nums.average { it * 10 } assert 3 == strings.average { it.size() } assert 3 == strings.average (String::size)
closure
- a single parameter closure that returns a (typically) numeric value.Chops the array into pieces, returning lists with sizes corresponding to the supplied chop sizes. If the array isn't large enough, truncated (possibly empty) pieces are returned. Using a chop size of -1 will cause that piece to contain all remaining items from the array.
chopSizes
- the sizes for the returned piecesCollates an array.
size
- the length of each sub-list in the returned listCollates this array into sub-lists.
size
- the length of each sub-list in the returned listkeepRemainder
- if true, any remaining elements are returned as sub-lists. Otherwise they are discardedCollates an array into sub-lists.
size
- the length of each sub-list in the returned liststep
- the number of elements to step through for each sub-listCollates this array into sub-lists.
size
- the length of each sub-list in the returned liststep
- the number of elements to step through for each sub-listkeepRemainder
- if true, any remaining elements are returned as sub-lists. Otherwise they are discardedIterates through this Array transforming each item into a new value using the
transform
closure, returning a list of transformed values.
transform
- the closure used to transform each item of the ArrayIterates through this Array transforming each item into a new value using the transform
closure
and adding it to the supplied collector
.
Integer[] nums = [1,2,3] Listanswer = [] nums.collect(answer) { it * 2 } assert answer == [2,4,6]
collector
- the Collection to which the transformed values are addedtransform
- the closure used to transform each itemA variant of collectEntries using the identity closure as the transform.
Iterates through this array transforming each item using the transform
closure
and returning a map of the resulting transformed entries.
def letters = "abc" def nums = [0, 1, 2] as Integer[] // collect letters with index using list style assert nums.collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] // collect letters with index using map style assert nums.collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']Note: When using the list-style of result, the behavior is '
def (key, value) = listResultFromClosure
'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
transform
- the closure used for transforming, which has an item from self as the parameter and
should return a Map.Entry, a Map or a two-element list containing the resulting key and valueA variant of collectEntries using the identity closure as the transform.
collector
- the Map into which the transformed entries are putIterates through this array transforming each item using the transform
closure
and returning a map of the resulting transformed entries.
def letters = "abc" def nums = [0, 1, 2] as Integer[] // collect letters with index assert nums.collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] assert nums.collectEntries( [4:'d'] ) { index -> [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']Note: When using the list-style of result, the behavior is '
def (key, value) = listResultFromClosure
'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
collector
- the Map into which the transformed entries are puttransform
- the closure used for transforming, which has an item from self as the parameter and
should return a Map.Entry, a Map or a two-element list containing the resulting key and valueA variant of collectEntries for arrays with separate functions for transforming the keys and values. The supplied collector map is used as the destination for transformed entries.
collector
- the Map into which the transformed entries are putkeyTransform
- a function for transforming array elements into keysvalueTransform
- a function for transforming array elements into valuesA variant of collectEntries for arrays with separate functions for transforming the keys and values.
String[] languages = ['Groovy', 'Java', 'Kotlin', 'Scala'] def firstLetter = (s) -> s[0] assert languages.collectEntries(firstLetter, String::size) == [G:6, J:4, K:6, S:5]
keyTransform
- a function for transforming array elements into keysvalueTransform
- a function for transforming array elements into valuesProjects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list.
def nums = [1, 2, 3, 4, 5, 6] as Object[] def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] } assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
projection
- a projecting Closure returning a collection of itemsProjects each item from a source array to a collection and concatenates (flattens) the resulting collections into a single list.
def nums = [1, 2, 3, 4, 5, 6] as Object[] def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] } assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]
collector
- an initial collection to add the projected items toprojection
- a projecting Closure returning a collection of itemsChecks whether the array contains the given value.
value
- the value being searched forCounts the number of occurrences which satisfy the given closure from inside this array.
predicate
- a closure conditionCounts the number of occurrences of the given value inside this array.
Comparison is done using Groovy's == operator (using
compareTo(value) == 0
or equals(value)
).
value
- the value being searched forCreates a multiset-like map of the array members.
Example usage:
assert [1:2, 2:2, 3:1] == ([1,2,1,2,3] as Object[]).countBy()
Sorts all array members into groups determined by the supplied mapping closure and counts the group size. The closure should return the key that each item should be grouped by. The returned Map will have an entry for each distinct key returned from the closure, with each value being the frequency of items occurring for that group.
Example usage:
assert ([1,2,2,2,3] as Object[]).countBy{ it % 2 } == [1:2, 0:3]
closure
- a closure mapping items to the frequency keysDrops the given number of elements from the head of this array if they are available.
String[] strings = [ 'a', 'b', 'c' ] assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] as String[] assert strings.drop( 2 ) == [ 'c' ] as String[] assert strings.drop( 5 ) == [] as String[]
num
- the number of elements to drop from this arraynum
ones, or else the empty array, if this
array has less than num
elements.Drops the given number of elements from the tail of this array if they are available.
String[] strings = [ 'a', 'b', 'c' ] assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ] as String[] assert strings.dropRight( 2 ) == [ 'a' ] as String[] assert strings.dropRight( 5 ) == [] as String[]
num
- the number of elements to drop from this arraynum
ones, or else the empty array, if this
array has less than num
elements.Create a suffix of the given array by dropping as many elements as possible from the front of the original array such that calling the given closure condition evaluates to true when passed each of the dropped elements.
def nums = [ 1, 3, 2 ] as Integer[] assert nums.dropWhile{ it<=
3 } == [ ] as Integer[] assert nums.dropWhile{ it<
3 } == [ 3, 2 ] as Integer[] assert nums.dropWhile{ it != 2 } == [ 2 ] as Integer[] assert nums.dropWhile{ it == 0 } == [ 1, 3, 2 ] as Integer[]
condition
- the closure that must evaluate to true to
continue dropping elementsIterates through an array passing each array entry to the given closure.
String[] letters = ['a', 'b', 'c'] String result = '' letters.each{ result += it } assert result == 'abc'
closure
- the closure applied on each array entryIterates through an array, passing each array element and the element's index (a counter starting at zero) to the given closure.
String[] letters = ['a', 'b', 'c']
String result = ''
letters.eachWithIndex{ letter, index ->
result += "$index:$letter" }
assert result == '0:a1:b2:c'
closure
- a Closure to operate on each array entryDetermines if the contents of this array are equal to the
contents of the given list, in the same order. This returns
false
if either collection is null
.
right
- the List being comparedtrue
if the contents of both collections are equal.Used to determine if the given predicate closure is valid (i.e. returns
true
for all items in this Array).
predicate
- the closure predicate used for matchingFinds the first element in the array that matches the given closure condition. Example:
def list = [1,2,3] as Integer[] assert 2 == list.find { it>
1 } assert null == list.find { it>
5 }
condition
- a closure conditionFinds the elements of the array matching the IDENTITY Closure (i.e. matching Groovy truth).
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Object[] assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
Finds all elements of the array matching the given Closure condition.
def items = [1,2,3,4] as Integer[] assert [2,4] == items.findAll { it % 2 == 0 }
condition
- a closure conditionIterates over the elements of an array and returns the index of the first item that satisfies the condition specified by the closure.
condition
- the matching conditionIterates over the elements of an array, starting from a specified index, and returns the index of the first item that satisfies the condition specified by the closure.
startIndex
- start matching from this indexcondition
- the matching conditionIterates over the elements of an array and returns the index values of the items that match the condition specified in the closure.
condition
- the matching conditionIterates over the elements of an array, starting from a specified index, and returns the index values of the items that match the condition specified in the closure.
startIndex
- start matching from this indexcondition
- the matching conditionReturns the index of the last item that matches the specified condition.
def array = new Number[]{1, 2, 1, 2, 1} assert array.findLastIndexOf{it==1} == 4 assert array.findLastIndexOf{it==2} == 3 assert array.findLastIndexOf{it==3} == -1 assert array.findLastIndexOf{it>=0} == 4 assert array.findLastIndexOf{it<=0} == -1 def empty = new Object[0] assert empty.findLastIndexOf {true} == -1
condition
- the matching conditionReturns the index of the last item that matches the specified condition that is at or beyond the given index.
def array = new Number[]{3, 1, 2, 1, 2, 1} assert array.findLastIndexOf(1,{it==0}) == -1 assert array.findLastIndexOf(1,{it==1}) == 5 assert array.findLastIndexOf(1,{it==2}) == 4 assert array.findLastIndexOf(1,{it==3}) == -1 assert array.findLastIndexOf(0,{it==3}) == 0 def empty = new Object[0] assert empty.findLastIndexOf( 2,{true}) == -1 assert empty.findLastIndexOf(-2,{true}) == -1
lowerBound
- the minimum indexcondition
- the matching conditionIterates through the Array stopping once the first non-null result is found and returning that result. If all results are null, null is returned.
Iterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all results are null, null is returned.
condition
- a closure that returns a non-null value to indicate that processing should stop and the value should be returnedIterates through the Array stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned.
defaultResult
- an Object that should be returned if all elements are nullIterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned.
defaultResult
- a value that should be returned if all closure results are nullcondition
- a closure that returns a non-null value to indicate that processing should stop and the value should be returnedIterates through the Array collecting any non-null results.
Iterates through the Array transforming items using the supplied closure and collecting any non-null results.
filteringTransform
- a closure that should return either a non-null transformed value or null for items which should be discardedReturns the first item from the array.
def array = [3, 4, 2].toArray() assert array.first() == 3
Flattens an array. This array and any nested arrays or collections have their contents (recursively) added to the new collection.
Flatten an array. This array and any nested arrays, collections or optionals have their contents (recursively) added to a new collection. A transform is applied to any leaf nodes before further flattening.
transform
- a transform applied to any leaf elementsSupports the subscript operator for an object array with an EmptyRange.
range
- an EmptyRangeSupports the subscript operator for an object array with an IntRange giving the desired indices.
range
- an IntRangeSupports the subscript operator for an object array with an ObjectRange giving the desired indices.
range
- an ObjectRangeSupports the subscript operator for an object array with a range giving the desired indices.
range
- a RangeSelects a List of items from an array using a Collection to identify the indices to be selected.
indices
- a collection of indicesReturns indices of the array.
Example:
String[] letters = ['a', 'b', 'c', 'd']
assert 0..<4 == letters.indices
Iterates over the array returning each element that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
Example:
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Object[] assert items.grep() == [1, 2, true, 'foo', [4, 5]]
Iterates over the array of items and returns a collection of items that match the given filter - calling the DefaultGroovyMethods#isCase(Object,Object) method used by switch statements. This method can be used with different kinds of filters like regular expressions, classes, ranges etc. Example:
def items = ['a', 'b', 'aa', 'bc', 3, 4.5] as Object[] assert items.grep( ~/a+/ ) == ['a', 'aa'] assert items.grep( ~/../ ) == ['aa', 'bc'] assert items.grep( Number ) == [ 3, 4.5 ] assert items.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
filter
- the filter to perform on each element of the array (using the DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object) method)Sorts all array members into groups determined by the supplied mapping closure. The closure should return the key that this item should be grouped by. The returned LinkedHashMap will have an entry for each distinct key returned from the closure, with each value being a list of items for that group.
Example usage:
Integer[] items = [1,2,3,4,5,6] assert [0:[2,4,6], 1:[1,3,5]] == items.groupBy { it % 2 }
closure
- a closure mapping entries on keysSorts all array members into (sub)groups determined by the supplied mapping closures as per the Iterable variant of this method.
closures
- an array of closures, each mapping entries on keysSorts all array members into (sub)groups determined by the supplied mapping closures as per the list variant of this method.
closures
- a list of closures, each mapping entries on keysReturns the first item from the Object array.
def array = [3, 4, 2].toArray() assert array.head() == 3
Returns the index of the first occurrence of the specified element in the
array. That is, the lowest index i
such that
Objects.equals(array[i], object)
or -1 if there is no such index.
String[] array = ['foo','bar','foo'] assert array.indexOf('foo') == 0 assert array.indexOf('bar') == 1 assert array.indexOf('baz') == -1 assert array.indexOf(12345) == -1
Returns the items from the Object array excluding the last item.
String[] strings = ["a", "b", "c"] def result = strings.init() assert result.length == 2 assert strings.class.componentType == String
Iterates through the given array, passing the first two elements to the closure. The result is passed back (injected) to the closure along with the third element and so on until all array elements have been consumed.
def array = new Number[] {1, 2, 3, 4} def value = array.inject { acc, val -> acc * val } assert value == 24 array = new Object[] {['a','b'], ['b','c'], ['d','b']} value = array.inject { acc, val -> acc.intersect(val) } assert value == ['b'] array = new String[] {'t', 'i', 'm'} value = array.inject { acc, val -> acc + val } assert value == 'tim'
closure
- a closureIterates through the given array, passing in the initial value and the first element to the closure. The result is sent back (injected) with the second element. The new result is injected back into the closure with the third element and so on until all elements have been consumed.
def array = new Number[] {2, 3, 4} def value = array.inject(1) { acc, val -> acc * val } assert value == 24 array = new Object[] {['a','b'], ['b','c'], ['d','b']} value = array.inject(['a','b','c']) { acc, val -> acc.intersect(val) } assert value == ['b'] array = new String[] {'t', 'i', 'm'} value = array.inject("") { acc, val -> acc + val } assert value == 'tim'
initialValue
- base valueclosure
- a closureReturns an Iterator which traverses the given array in index order.
Concatenates the string representation of each item in this array.
def array = new Number[]{1,2L,3G} assert array.join() == "123"
Concatenates the string representation of each item in this array, with the given String as a separator between each item.
Serializable[] array = [1,2L,-3G] assert array.join("+") == "1+2+-3"
separator
- a String separatorReturns the last item from the array.
def array = [3, 4, 2].toArray() assert array.last() == 2
Returns the index of the last occurrence of the specified element in the
array. That is, the highest index i
such that
Objects.equals(array[i], object)
or -1 if there is no such index.
String[] array = ['foo','bar','foo'] assert array.lastIndexOf('foo') == 2 assert array.lastIndexOf('bar') == 1 assert array.lastIndexOf('baz') == -1 assert array.lastIndexOf(12345) == -1
Adds max() method to Object arrays.
Selects the maximum value found from the Object array using the closure to determine the correct ordering.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
closure
- a Closure used to determine the correct orderingSelects the maximum value found from the Object array using the given comparator.
comparator
- a ComparatorAdds min() method to Object arrays.
Selects the minimum value found from the Object array using the closure to determine the correct ordering.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
closure
- a Closure used to determine the correct orderingSelects the minimum value found from the Object array using the given comparator.
comparator
- a ComparatorCreates a new array composed of the elements of the first array minus the elements of the given Iterable.
Integer[] ints = [1, 2, 3, 1] List<Integer> nope = [1, 3] def result = ints - nope assert result.class == Integer[] assert result == new Integer[]{2} Integer[] none = [] result = none - 123 assert result !== none assert result.length == 0 assert result.class == Integer[]
removeMe
- an Iterable of elements to removeCreates a new array composed of the elements of the given array minus every occurrence the given object.
Integer[] ints = [1, 2, 3, 1] def result = ints - 1 assert result.class == Integer[] assert result == new Integer[]{2, 3} Integer[] none = [] result = none - '1' assert result !== none assert result.length == 0 assert result.class == Integer[]
removeMe
- an element to remove from the arrayCreates a new array composed of the elements of the first array minus the elements of the given array.
Integer[] ints = [1, 2, 3, 1] Integer[] nope = [1, 3] def result = ints - nope assert result.class == Integer[] assert result == new Integer[]{2} Integer[] none = [] result = none - 123 assert result !== none assert result.length == 0 assert result.class == Integer[]
removeMe
- an array of elements to removeCreates an array containing elements from an original array plus those from an Iterable.
class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } String[] array = ['x', 'y', 'z'] def result = array + new AbcIterable() assert result.class == String[] assert result == new String[]{'x', 'y', 'z', 'a', 'b', 'c'}
right
- an Iterable to be appendedCreates an array containing elements from an original array plus an additional appended element.
Integer[] a = [1, 2, 3] def result = a + 4 assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, 4} result = a + 5.5d assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, 5} // improper type arguments; Date can't be coerced to Integer groovy.test.GroovyAssert.shouldFail(ClassCastException) { a + new Date() }
right
- the value to appendCreates an array as a union of two arrays.
Integer[] a = [1, 2, 3] Integer[] b = [4, 5, 6] def result = a + b assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, 4, 5, 6} Number[] c = [-1, 0.9, null] result = c + a assert result.class == Number[] assert result == new Number[]{-1, 0.9, null, 1, 2, 3} result = a + c assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, -1, 0, null} Date[] d = [new Date()] // improper type arguments; Date can't be coerced to Integer groovy.test.GroovyAssert.shouldFail(ClassCastException) { a + d }
right
- the right ArrayCreates an array containing elements from an original array plus those from a Collection.
Integer[] a = [1, 2, 3] def result = a + [4, 5, 6] assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, 4, 5, 6} Number[] c = [-1, 0.9, null] result = c + [1, 2, 3] assert result.class == Number[] assert result == new Number[]{-1, 0.9, null, 1, 2, 3} result = a + [-1, 0.9, null] assert result.class == Integer[] assert result == new Integer[]{1, 2, 3, -1, 0, null} // improper type arguments; Date can't be coerced to Integer groovy.test.GroovyAssert.shouldFail(ClassCastException) { a + [new Date()] }
right
- a Collection to be appendedCreates a new array containing items which are the same as this array but in reverse order.
Reverses the items in an array. If mutate is true, the original array is modified in place and returned. Otherwise, a new array containing the reversed items is produced.
def array = new Object[] {1,2,3} def yarra = array.reverse(true) assert array == 3..1 assert yarra == 3..1 yarra = array.reverse(false) assert array == 3..1 assert yarra == 1..3
mutate
- true
if the array itself should be reversed in place, false
if a new array should be createdIterates over each element of the array in the reverse order.
closure
- a closure to which each item is passedRandomly reorders the elements of the specified array.
Integer[] array = [10, 5, 20] def origSize = array.size() def items = array.toList() array.shuffle() assert array.size() == origSize assert items.every{ array.contains(it) }
Randomly reorders the elements of the specified array using the specified random instance as the source of randomness.
def r = new Random() Integer[] array = [10, 5, 20] def origSize = array.size() def items = array.toList() array.shuffle(r) assert array.size() == origSize assert items.every{ array.contains(it) }
Creates a new array containing the elements of the specified array but in a random order.
Integer[] array = [10, 5, 20] def result = array.shuffled() assert array !== result assert array.length == result.length assert array.every{ result.contains(it) } assert array == new Integer[] {10, 5, 20}
Creates a new array containing the elements of the specified array but in a random order using the specified random instance as the source of randomness.
def r = new Random() Integer[] array = [10, 5, 20] def result = array.shuffled(r) assert array !== result assert array.length == result.length assert array.every{ result.contains(it) } assert array == new Integer[] {10, 5, 20}
Provides the standard Groovy size()
method for an array.
Modifies this array so that its elements are in sorted order. The array items are assumed to be comparable.
Sorts the given array into sorted order. The array items are assumed to be comparable. If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted array is returned and the original array remains unchanged.
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false) assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["Hey","hello","hi"] as String[] orig.sort(true) assert orig == ["Hey","hello","hi"] as String[]
mutate
- false will always cause a new array to be created, true will mutate the array in placeModifies this array so that its elements are in sorted order using the Closure to determine the correct ordering. If mutate is false, a new array is returned and the original array remains unchanged. Otherwise, the original array is sorted in place and returned.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false) { it.size() } assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["hi","Hey","hello"] as String[] orig.sort(true) { it.size() } assert orig == ["hi","Hey","hello"] as String[]
mutate
- false will always cause a new array to be created, true will mutate arrays in placeclosure
- a Closure used to determine the correct orderingModifies this array so that its elements are in sorted order as determined by the given comparator. If mutate is true, the array is sorted in place and returned. Otherwise, a new sorted array is returned and the original array remains unchanged.
def orig = ["hello","hi","Hey"] as String[] def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","hi","Hey"] as String[] assert sorted == ["hello","Hey","hi"] as String[] orig.sort(true, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","Hey","hi"] as String[]
mutate
- false will always cause a new array to be created, true will mutate arrays in placecomparator
- a Comparator used for the comparisonSorts the elements from this array into a newly created array using the Closure to determine the correct ordering.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
closure
- a Closure used to determine the correct orderingSorts the given array into sorted order using the given comparator.
comparator
- a Comparator used for the comparisonSplits all items into two collections based on the closure condition. The first list contains all items which match the closure expression. The second list all those that don't.
closure
- a closure conditionReturns a sequential Stream with the specified array as its source.
Stream
for the arraySums the items in an array. This is equivalent to invoking the "plus" method on all items in the array.
Sums the result of applying a closure to each item of an array.
array.sum(closure)
is equivalent to:
array.collect(closure).sum()
.
closure
- a single parameter closure that returns a (typically) numeric value.Sums the items in an array, adding the result to some initial value.
initialValue
- the items in the array will be summed to this initial valueSums the result of applying a closure to each item of an array to some initial value.
array.sum(initVal, closure)
is equivalent to:
array.collect(closure).sum(initVal)
.
closure
- a single parameter closure that returns a (typically) numeric value.initialValue
- the closure results will be summed to this initial valueSwaps two elements at the specified positions.
Example:
assert (["a", "c", "b", "d"] as String[]) == (["a", "b", "c", "d"] as String[]).swap(1, 2)
i
- a positionj
- a positionReturns the items from the array excluding the first item.
String[] strings = ["a", "b", "c"] def result = strings.tail() assert result.class.componentType == String String[] expected = ["b", "c"] assert result == expected
Returns the first num
elements from the head of this array.
String[] strings = [ 'a', 'b', 'c' ] assert strings.take( 0 ) == [] as String[] assert strings.take( 2 ) == [ 'a', 'b' ] as String[] assert strings.take( 5 ) == [ 'a', 'b', 'c' ] as String[]
num
- the number of elements to take from this arraynum
elements of this array,
or else the whole array if it has less than num
elements.Returns the last num
elements from the tail of this array.
String[] strings = [ 'a', 'b', 'c' ] assert strings.takeRight( 0 ) == [] as String[] assert strings.takeRight( 2 ) == [ 'b', 'c' ] as String[] assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ] as String[]
num
- the number of elements to take from this arraynum
elements of this array,
or else the whole array if it has less than num
elements.Returns the longest prefix of this array where each element passed to the given closure evaluates to true.
def nums = [ 1, 3, 2 ] as Integer[] assert nums.takeWhile{ it<
1 } == [] as Integer[] assert nums.takeWhile{ it<
3 } == [ 1 ] as Integer[] assert nums.takeWhile{ it<
4 } == [ 1, 3, 2 ] as Integer[]
condition
- the closure that must evaluate to true to
continue taking elementsConverts this array to a List of the same size, with each element added to the list.
Converts this array to a Set, with each unique element added to the set.
Returns a sorted version of the given array using the supplied comparator.
Sorts the elements from this array into a newly created array using the Closure to determine the correct ordering.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
closure
- a Closure used to determine the correct orderingReturns a sorted version of the given array using the supplied comparator to determine the resulting order.
def sumDigitsComparator = [compare: { num1, num2->
num1.toString().toList()*.toInteger().sum()<=>
num2.toString().toList()*.toInteger().sum() }] as Comparator Integer[] nums = [9, 44, 222, 7000] def result = nums.toSorted(sumDigitsComparator) assert result instanceof Integer[] assert result == [222, 7000, 44, 9]
comparator
- a Comparator used for the comparisonCreates a spreadable map from this array.
Returns the string representation of the given array.
Returns a new Array containing the items from the original Array but with duplicates removed using the natural ordering of the items in the array.
String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't'] String[] expected = ['c', 'a', 't', 's', 'h'] def result = letters.toUnique() assert result == expected assert result.class.componentType == String
Returns a new Array containing the items from the original Array but with duplicates removed with the supplied closure determining which items are unique.
String[] letters = ['c', 'a', 't', 's', 'A', 't', 'h', 'a', 'T'] String[] expected = ['c', 'a', 't', 's', 'h'] assert letters.toUnique{ p1, p2->
p1.toLowerCase()<=>
p2.toLowerCase() } == expected assert letters.toUnique{ it.toLowerCase() } == expected
closure
- a Closure used to determine unique itemsReturns a new Array containing the items from the original Array but with duplicates removed with the supplied comparator determining which items are unique.
String[] letters = ['c', 'a', 't', 's', 'A', 't', 'h', 'a', 'T']
String[] lower = ['c', 'a', 't', 's', 'h']
class LowerComparator implements Comparator {
int compare(a, b) { a.toLowerCase() <=>
b.toLowerCase() }
}
assert letters.toUnique(new LowerComparator()) == lower
comparator
- a Comparator used to determine unique (equal) items
If null
, the Comparable natural ordering of the elements will be used.Creates an Object array containing elements from an original array plus those from an Iterable. This is similar to Object[]#plus(Iterable) but always return an Object array and so might be more applicable when adding heterogeneous arrays.
class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } String[] array = ['x', 'y', 'z'] def result = array.union(new AbcIterable()) assert result.class == Object[] assert result == new Object[]{'x', 'y', 'z', 'a', 'b', 'c'}
right
- an Iterable to be appendedCreates an Object array containing elements from an original array plus an additional appended element. This is similar to Object[]#plus(Object) but always return an Object array and so might be more applicable when adding heterogeneous arrays.
Integer[] a = [1, 2, 3] def result = a.union('foo') assert result.class == Object[] assert result == new Object[]{1, 2, 3, 'foo'}
right
- the value to appendCreates an Object array as a union of two arrays. This is similar to Object[]#plus(Object[]) but always return an Object array and so might be more applicable when adding heterogeneous arrays.
Integer[] a = [1, 2, 3] String[] b = ['foo', 'bar'] def result = a.union(b) assert result.class == Object[] assert result == new Object[]{1, 2, 3, 'foo', 'bar'}
right
- the right ArrayCreates an object array containing elements from an original array plus those from a Collection. This is similar to Object[]#plus(Collection) but always return an Object array and so might be more applicable when adding heterogeneous arrays.
Integer[] a = [1, 2, 3] def result = a.union(['foo', 'bar']) assert result.class == Object[] assert result == new Object[]{1, 2, 3, 'foo', 'bar'}
right
- a Collection to be appendedA variant of withCollectedKeys for arrays.
collector
- the Map into which the transformed entries are putkeyTransform
- a function for transforming array elements into valuesA variant of withCollectedKeys for arrays.
keyTransform
- a function for transforming array elements into valuesA variant of withCollectedValues for arrays.
collector
- the Map into which the transformed entries are putvalueTransform
- a function for transforming array elements into values